package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ghost on 2014/12/23 0023.
 */
public class Excel_Sheet_Column_Title {
    public String convertToTitle(int n) {
        int a = n / 26;
        int b = n % 26;
        List<Character> Rst = new ArrayList<Character>();
        ArrayList<Integer> rst = new ArrayList<Integer>();
        while (a != 0) {
            rst.add(b);
            int tmp = a;
            a = tmp / 26;
            b = tmp % 26;
        }
        rst.add(b);
        for (int i = 0; i < rst.size(); i++) {
            if (rst.get(i) == 0) {
                int j = i + 1;
                for (; j < rst.size() && rst.get(j) == 0; j++) {
                    rst.set(j, 26);
                }
                if (j < rst.size()) {
                    rst.set(j, rst.get(j) - 1);
                }
                if (i != rst.size() - 1)
                    Rst.add('Z');
            } else {
                Rst.add((char) ('A' - 1 + rst.get(i)));
            }
        }
        StringBuffer sb = new StringBuffer("");
        for (int i = Rst.size() - 1; i >= 0; i--)
            sb.append(Rst.get(i));
        return sb.toString();
    }

    public static void main(String[] args) {
        Excel_Sheet_Column_Title excel_sheet_column_title = new Excel_Sheet_Column_Title();
        System.out.println(excel_sheet_column_title.convertToTitle(388));
    }
}
